
# 目前情况：安装不成功：pip install pyautogui opencv-python pillow

# 办公室台式机，可以

from selenium import webdriver
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import threading
import time
import cv2
import numpy as np
import pyautogui


class ScreenRecorder:
    def __init__(self, filename="recording.avi"):
        self.filename = filename
        self.recording = False
        self.fourcc = cv2.VideoWriter_fourcc(*"XVID")
        self.out = None

    def start_recording(self):
        """开始录屏"""
        self.recording = True
        # 获取屏幕尺寸
        screen_size = pyautogui.size()
        self.out = cv2.VideoWriter(self.filename, self.fourcc, 10.0, screen_size)

        def record():
            while self.recording:
                try:
                    # 截屏
                    img = pyautogui.screenshot()
                    frame = np.array(img)
                    frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
                    self.out.write(frame)
                    time.sleep(0.1)
                except Exception as e:
                    print(f"录屏错误: {e}")
                    break

        self.thread = threading.Thread(target=record)
        self.thread.start()
        print("🎥 开始录屏...")

    def stop_recording(self):
        """停止录屏"""
        self.recording = False
        if self.thread:
            self.thread.join()
        if self.out:
            self.out.release()
        print(f"💾 录屏已保存: {self.filename}")


# 主程序
def create_driver():
    options = Options()
    options.add_argument('--no-sandbox')
    options.add_experimental_option("detach", True)
    driver_edge = webdriver.Edge(options=options)
    return driver_edge


# 创建录屏对象
recorder = ScreenRecorder("bilibili_hover_recording.avi")
driver = create_driver()

try:
    # 开始录屏
    recorder.start_recording()

    print("开始执行自动化操作...")
    driver.get("https://www.bilibili.com/")
    driver.maximize_window()

    # 找到需要悬停的元素
    el_hover = driver.find_element(By.XPATH, '//*[@id="i_cecream"]/div[2]/div[1]/div[1]/ul[1]/li[6]/a/span')

    # 执行悬停操作
    actions = ActionChains(driver)
    actions.move_to_element(el_hover).perform()
    print("鼠标停在了漫画上")
    time.sleep(1)

    # 执行点击操作
    subel_hover = driver.find_element(By.XPATH,
                                      '//*[@id="i_cecream"]/div[2]/div[1]/div[1]/ul[1]/li[6]/div/div/div/div[2]/div[2]/div[1]')
    actions.click(subel_hover).perform()
    print("我已经点击了第一条链接")

    # 获取全部标签页、句柄
    handles = driver.window_handles
    print(handles)

    # 关闭之前标签页
    driver.close()

    # 通过句柄切换标签页
    driver.switch_to.window(handles[1])

    # 获取当前标签页的句柄
    handles = driver.current_window_handle
    print(f'当前控制标签页的句柄为：{handles}')

    # 隐式等待
    driver.implicitly_wait(30)
    sub_title = driver.find_element(By.XPATH, '/html/body/div[1]/div/div[1]/div[2]/div[1]/div[2]/h1')

    if sub_title.text == '不小心救了江湖公敌':
        print("测试成功！")

    time.sleep(2)

    # 停止录屏
    recorder.stop_recording()
    print("🎉 操作完成！视频已保存")

except Exception as e:
    print(f"错误: {e}")
    recorder.stop_recording()
finally:
    driver.quit()